from MyTableView import MyTableView
from objectview import ObjectModel
import logging
from delegates import NotEditDelegate,FloatEditDelegateQt,EditDelegateQt,DateTimeEditDelegateQt,DoubleViewDelegate,ComboBoxDelegateQt,DateTimeEditDelegateQt
import logging
from PyQt5.QtCore import QPoint, Qt, QCoreApplication, pyqtSlot
from PyQt5.QtGui import  QBrush, QPixmap, QColor, QPainter,QIcon,QPolygon
from PyQt5 import QtWidgets,QtCore
from PyQt5.QtCore import pyqtSignal
import myglobal
from ui_biaoye import Ui_Form
import numpy
class Row():
    def __init__(self):
        self.bw=""
        self.w1=0
        self.m0=0
        self.V1=0
        self.V2=0
        self.V3=0
        self.V4=0
        self.c=0
        self.V5=0
        self.V6=0
        self.V7=0
        self.V8=0
class BiaoYe(QtWidgets.QWidget):
    def __init__(self,parent=None):
        super().__init__(parent)
        self.m=51.996
        self.c0=0
        self.c1=1.000
        self.c=0
        self.V9=0
        self.ui=Ui_Form()
        self.ui.setupUi(self)       
        self.dblViewDele = DoubleViewDelegate("%.07f")
        self.dateDelegate=DateTimeEditDelegateQt()#
        self.editDelegate=EditDelegateQt()
        self.floatEdit=FloatEditDelegateQt()
        self.comboDelegate=ComboBoxDelegateQt(["圆管","棒材","板材","剖管","扁钢丝"])
        self.notedit=NotEditDelegate()
        self.properties = [
            {"ele":None,"delegate":"floatEdit",'width':130,'attr': "bw",'visible':True,  'header': "标物名称"},
            {"ele":None,"delegate":"floatEdit",'width':130,'attr': "w1",'visible':True,  'header': "认定值%"},
            {"ele":None,"delegate":"floatEdit",'width':130,'attr': "m0",'visible':True,  'header': "标钢质量"},
            {"ele":None,"delegate":"floatEdit",'width':130,'attr': "V1",'visible':True,  'header': "定容V1"},
            {"ele":None,"delegate":"floatEdit",'width':130,'attr': "V2",'visible':True,  'header': "分取V2"},
            {"ele":None,"delegate":"floatEdit",'width':80,'attr': "V3",'visible':True,  'header': "标液体积V3"},
            {"ele":None,"delegate":"floatEdit",'width':80,'attr': "V4",'visible':True,  'header': "滴定体积V4"},
            {"ele":None,"delegate":"double",'width':80,'attr': "c",'visible':True,  'header': "滴定溶液浓度c"},
            {"ele":None,"delegate":"floatEdit",'width':130,'attr': "V5",'visible':True,  'header': "溶液体积V5"},
            {"ele":None,"delegate":"floatEdit",'width':80,'attr': "V6",'visible':True,  'header': "第一次滴定V6"},
            {"ele":None,"delegate":"floatEdit",'width':80,'attr': "V7",'visible':True,  'header': "第二次滴定V7"},
            {"ele":None,"delegate":"double",'width':80,'attr': "V8",'visible':True,  'header': "校正体积V8"},
        ]
        self.objs=[]
        for i in range(3):
            one=Row()
            self.objs.append(one)
        self.model = ObjectModel()
        self.model.setObjects(self.objs,self.properties)
        self.ui.pushButton_calc.clicked.connect(self.calc)
        self.ui.table.setModel(self.model)
        self.ui.table.dragbottom.connect(self.dragbottom_trig)
        self.ui.table.setMaximumSize(QtCore.QSize(1228899, 120))
        self.ui.lineEdit_c0.setText(str(self.c0))
        self.ui.lineEdit_c0.editingFinished.connect(self.c0_edit)
        self.ui.lineEdit_c1.editingFinished.connect(self.c1_edit)
        self.ui.lineEdit_m.editingFinished.connect(self.m_edit)
        self.ui.lineEdit_c1.setText(str(self.c1))
        self.ui.lineEdit_m.setText(str(self.m))
        for i, prop in enumerate(self.properties):
            logging.info([i,prop])
            if prop.get('delegate')=="edit":
                self.ui.table.setItemDelegateForColumn(i, self.editDelegate)
            elif prop.get('delegate')=="floatEdit":
                self.ui.table.setItemDelegateForColumn(i, self.floatEdit)
            elif prop.get('delegate')=="double":
                self.ui.table.setItemDelegateForColumn(i, self.dblViewDele)
            elif prop.get('delegate')=="comboEdit":
                self.ui.table.setItemDelegateForColumn(i, self.comboDelegate)
            elif prop.get('delegate')=="date":
                self.ui.table.setItemDelegateForColumn(i, self.dateDelegate)
            elif prop.get('delegate')==None:
                self.ui.table.setItemDelegateForColumn(i, self.notedit)
    def paste(self):
        clipboard = QtWidgets.QApplication.clipboard()
        t = clipboard.text()
        logging.info(t)
        if t != "":
            # ,"uni_cs","uni_on"]:
            objs=self.import_text_bytitle(t)  # clip board from excel
            print(self.objs)
            self.objs=[]
            for one in objs:
                self.objs.append(one)
            print(self.objs)
            self.refresh_grid2()
    def import_text_bytitle(self, txt):
        logging.info(txt)
        data = []
        for row in txt.split("\n"):
            # logging.info(row)
            data.append(row.split("\t"))
        title = data[0]
        data = data[1:]
        logging.info(title)
        for f in self.properties:
            if f['attr']=="bw":
                f["at"] =0 
            elif f['attr']=="w1":
                f["at"] =1
            elif f['attr']=="V3":
                f["at"] =2
            elif f['attr']=="V4":
                f["at"] =4                
            elif f['attr']=="V5":
                f["at"] =8
            elif f['attr']=="V6":
                f["at"] =9
            elif f['attr']=="V7":
                f["at"] =11                                
            else:
                f["at"]=-1
        r=[]
        for one in data:
            # logging.info("=====================")
            logging.info(one)
            if len(one) < 2:
                continue
            fs = []
            vs = []
            for f in self.properties:
                if f["at"] != -1:
                    logging.info([f["header"],f["at"]])
                    try:
                        fs.append( f["attr"])
                        vs.append(one[f["at"]] )
                    except IndexError:
                        pass
            print(fs,vs)
            s=Row()
            for i in range(len(fs)):
                try:
                    setattr(s,fs[i],myglobal.myfloat(vs[i]))
                except IndexError:
                    pass

            r.append(s)
        print(r)
        return r              
    def c0_edit(self):
        self.c0=myglobal.myfloat(self.ui.lineEdit_c0.text())
    def c1_edit(self):
        self.c0=myglobal.myfloat(self.ui.lineEdit_c0.text())
    def m_edit(self):
        self.c0=myglobal.myfloat(self.ui.lineEdit_c0.text())
    def calcOne(self,row):
        #=IF(C5="","",IF(B5="",IF($E$2="",$P$2*C5/(E5+$Q$4),$E$2*C5/(E5+$Q$4)/$J$1),B5*C5*10/$J$1/(E5+$Q$4)))
        row.V8=row.V6-row.V7
        if row.V4==0:
            row.c=0
        else:
            if self.c0==0:
                if self.c1==0:
                    if row.V1==0:
                        fq=1
                    else:
                        fq=row.V2/row.V1
                    row.c=row.w1*row.m0*10*fq/((row.V4-self.V9)*self.m)
                else:
                    row.c=self.c1*row.V3/((row.V4-self.V9)*self.m)
            else:
                if row.V1==0:
                    fq=1
                else:
                    fq=row.V2/row.V1
                row.c=self.c0*fq
    def calcC(self):
        vs=[]
        for i in range(len(self.objs)):
            one=self.objs[i]
            vs.append(one.c)
        self.c=numpy.average(vs)
        self.ui.lineEdit_c.setText(str(self.c))
    def calcV9(self):
        vs=[]
        for i in range(len(self.objs)):
            one=self.objs[i]
            one.V8=one.V6-one.V7
            vs.append(one.V8)
        self.V9=numpy.average(vs)
        self.ui.lineEdit_V9.setText(str(self.V9))
    def calc(self):
        print("calc")
        self.calcV9()
        for i in range(len(self.objs)):
            one=self.objs[i]
            self.calcOne(one)
        self.calcC()
        self.refresh_grid2()
        pass
    def dragbottom_trig(self,indexs):
        print(indexs)  
        first_row=None
        cols=[]
        for i  in range(len(indexs)):
            first=indexs[i]
            row=first.row()
            col=first.column()
            print(row,col)
            if first_row==None:
                first_row=row
            if row==first_row:
                cols.append(col)
            else:
                break
        print(first_row,cols)
        obj=self.objs[first_row]
        for col in cols:
            print("col",col)
            v=getattr(obj,self.properties[col]["attr"])
            if self.properties[col]["delegate"]!=None:
                for one in indexs[len(cols):]:
                    print("row",one.row(),"col",one.column())
                    if one.column()==col:
                        print("change")
                        obj_to=self.objs[one.row()]
                        setattr(obj_to,self.properties[col]["attr"],v)
        self.refresh_grid2() 
    def refresh_grid2(self):
        # try:
        #     self.objs.sort(reverse=False, key=lambda a:a.num)
        # except TypeError:
        #     pass 
        self.model.setObjects(self.objs,self.properties)
        self.ui.table.setModel(self.model)
if __name__ == "__main__":
    import sys
    from PyQt5 import QtWidgets
    a = QtWidgets.QApplication(sys.argv)
    a.lastWindowClosed.connect(a.quit)
    by=BiaoYe(None)
    by.resize(1600,500)
    by.show()
    sys.exit(a.exec())
